﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bordspil.Models;

namespace Bordspil.Controllers
{
    public class KindoController : Controller
    {
        private IAppRepository m_repository = null;

        public KindoController()
        {
            m_repository = new AppRepository();
        }

        //public GameController(IAppRepository rep)
        //{
        //  m_repository = rep;
        // }
        //
        // GET: /Ludo/

        public ActionResult Index(int? id)
        {
            if (id == null)
            {
                //ef notandi byr til nyjan leik ta byr hann til nytt instance af tvi
                GameInstance newGame = new GameInstance();
                newGame.GameId = 1;
                newGame.PlayerName = User.Identity.Name;
                newGame.IsActive = true;
                newGame.NumberOfPlayers = 1;
                m_repository.AddGame(newGame);
                m_repository.Save();

                return View(newGame);
            }
            var result = (from game in m_repository.GetGames()
                          where game.InstanceId == id
                          select game).SingleOrDefault();

            if (result.NumberOfPlayers >= result.Games.MaxPlayers)
            {
                //ef of margir spilarar eru ta er fullur leikur (notendur sja samt ekki leik a sidunni sem eru fullir)
                return View("FullGame");
            }
            result.NumberOfPlayers += 1; //haekka fjolda spilara
            m_repository.Save();
            if (result != null)
            {
                //skila nidurstodum ef ekkert kemur uppa
                return View(result);
            }

            return View("NotFound");
        }
    }
}
